package other.up.demo;
import gnu.io.*;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.TooManyListenersException;

/**
 * @author bingo
 * @Description
 * @Date 2018/7/26
 */
public class MySerialPort implements Runnable,SerialPortEventListener {

    private CommPortIdentifier commPortIdentifier;

    private Enumeration<CommPortIdentifier> comPortList;

    private SerialPort serialPort;

    private InputStream inputStream;

    private OutputStream outputStream;
   @Test
    public void getAllAvailbleCom(){

        comPortList = CommPortIdentifier.getPortIdentifiers();
        while(comPortList.hasMoreElements()){
            commPortIdentifier = comPortList.nextElement();
           // System.out.println(commPortIdentifier.getCurrentOwner());
            System.out.println("串口名字:"+commPortIdentifier.getName());
            System.out.println("串类型:"+commPortIdentifier.getPortType());
        }
    }

    public void  open(){
        comPortList = CommPortIdentifier.getPortIdentifiers();
        while(comPortList.hasMoreElements()){
              commPortIdentifier = comPortList.nextElement();
              if(commPortIdentifier.getPortType()==CommPortIdentifier.PORT_SERIAL){
                  if ("COM5".equals(commPortIdentifier.getName())){
                      System.out.println("打开COM5~~~~");
                  try {
                      serialPort = (SerialPort) commPortIdentifier.open(Object.class.getSimpleName(),2000);
                      serialPort.addEventListener(this);
                      serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                      serialPort.notifyOnDataAvailable(true);
                  } catch (PortInUseException e) {
                      System.err.println("端口已经被占用!");
                      e.printStackTrace();
                  }catch (TooManyListenersException e){
                      e.printStackTrace();
                  } catch (UnsupportedCommOperationException e) {
                      e.printStackTrace();
                  }
                }
              }
        }
    }







    public static void main(String[] args) {
       Thread thread = new Thread(new MySerialPort());
       thread.start();
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        switch (serialPortEvent.getEventType()){

            case SerialPortEvent.BI:
                System.out.println("通讯中断");
            case SerialPortEvent.CD:
                System.out.println("载波检测");
            case SerialPortEvent.CTS:
                System.out.println("清除发送");
            case SerialPortEvent.DATA_AVAILABLE:
                System.out.println("有数据到达哦~~~~");
                readMessage();
                break;
            case SerialPortEvent.DSR:
                System.out.println("数据设备准备好");
            case SerialPortEvent.FE:
                System.out.println("帧错误");
            case SerialPortEvent.OE:
                System.out.println("溢位错误");
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                System.out.println("输出缓冲区已清空");
            case SerialPortEvent.PE:
                System.out.println("奇偶校验错误");
            case SerialPortEvent.RI:
                System.out.println("响铃侦测");
            default:
                break;
        }

    }
    /**读取串口信息*/
    public void readMessage() {
        byte[] bytes = new byte[1024];
        int len = 0;

        try {
            inputStream  = serialPort.getInputStream();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while ((len = inputStream.read(bytes))!=-1){
                  System.out.println("实时反馈:"+new String(bytes,0,len,"gbk").trim()+"  on  "+format.format(new Date()));
                  break;
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    /**发送消息*/
    public  void sendMesage(){
        String   msg = null;
        try {
            msg = new String("你好".getBytes(),"gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            outputStream = serialPort.getOutputStream();
            outputStream.write(msg.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void run() {
      open();
        System.out.println("opening~~~~~~~~~~~~~~~~~``");
        while (true){
            sendMesage();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //System.out.println("已经发送~~~~~~~~~~~~~~");
    }

}
